
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command
export default async function (ctx: FunctionContext) {
  let id = ctx.body._id
  if (nw.util.isNull(id)){
    return fail("参数不合法")
  }
  //查询优惠卷基本信息couponInfo
  let couponInfo = await nw.db.findById({
    dbName:"couponInfo",
    id:id
  })
  if (nw.util.isNull(couponInfo)){
    return fail("优惠券不存在")
  }
  //2.优惠卷id查询coupon_range 查询里面对应range_id
  let couponRange = await nw.db.findListByWhereJson({
    dbName:"couponRange",
    whereJson:{deleted:0,couponId:id}
  })
  if (nw.util.isNull(couponRange)||!nw.util.isArray(couponRange)||couponRange.length===0){
    return ok({})
  }
  //3.获取对应的数据规则
  let result = {skuInfoList:[],categoryList:[]}
  let skuIds = []
  let categoryIds = []

  for (let i = 0; i < couponRange.length; i++) {
    let range = couponRange[i]
    if (range.rangeType===3){
      skuIds.push(range.rangeId)
    }else if (range.rangeType===2){
      categoryIds.push(range.rangeId)
    }

  }

  if (skuIds.length>0){
    let skuInfos = await nw.db.findListByWhereJson({
      dbName:"skuInfo",
      whereJson:{deleted:0,_id:_.in(skuIds)}
    })
    result.skuInfoList = skuInfos
  }
  if (categoryIds.length>0){
    let categorys = await nw.db.findListByWhereJson({
      dbName:"category",
      whereJson:{deleted:0,_id:_.in(categoryIds)}
    })
    result.categoryList = categorys
  }

  return ok(result)
}
